package controller

import (
	"net/http"
	"strconv"

	"gitee.com/ysl729895/go-mall/internal/model"
	"gitee.com/ysl729895/go-mall/internal/service"
	"github.com/gin-gonic/gin"
)

// RoleController 角色管理控制器，处理角色相关的 HTTP 请求
// 包括角色的增删改查

type RoleController struct {
	service service.RoleService
}

// NewRoleController 构造函数，注入 RoleService
func NewRoleController(service service.RoleService) *RoleController {
	return &RoleController{service: service}
}

// CreateRole 创建新角色
// @Summary 创建角色
// @Tags 角色管理
// @Accept json
// @Produce json
// @Param role body model.Role true "角色信息"
// @Success 201 {object} model.Role
// @Router /api/roles [post]
func (c *RoleController) CreateRole(ctx *gin.Context) {
	var req struct {
		Name        string `json:"name" binding:"required"`
		Description string `json:"description"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, model.ErrorResponse{
			Code:    http.StatusBadRequest,
			Message: "请求参数格式不正确",
			Error:   err.Error(),
		})
		return
	}
	role := &model.Role{Name: req.Name, Description: req.Description}
	if err := c.service.CreateRole(req.Name, req.Description); err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, model.ErrorResponse{
			Code:    http.StatusInternalServerError,
			Message: "创建角色失败",
			Error:   err.Error(),
		})
		return
	}
	ctx.Set("responseData", role)
	ctx.Set("responseMessage", "创建角色成功")
	ctx.Status(http.StatusCreated)
}

// UpdateRole 通过 POST /update 实现角色更新
// @Summary 更新角色
// @Tags 角色管理
// @Accept json
// @Produce json
// @Param role body model.Role true "角色信息"
// @Success 200 {object} model.Role
// @Failure 400 {object} model.ErrorResponse
// @Failure 500 {object} model.ErrorResponse
// @Router /api/roles/update [post]
func (c *RoleController) UpdateRole(ctx *gin.Context) {
	var req struct {
		ID          uint   `json:"id" binding:"required"`
		Name        string `json:"name" binding:"required"`
		Description string `json:"description"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, model.ErrorResponse{
			Code:    http.StatusBadRequest,
			Message: "请求参数格式不正确",
			Error:   err.Error(),
		})
		return
	}
	if err := c.service.UpdateRole(req.ID, req.Name, req.Description); err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, model.ErrorResponse{
			Code:    http.StatusInternalServerError,
			Message: "更新角色失败",
			Error:   err.Error(),
		})
		return
	}
	ctx.Set("responseData", gin.H{"id": req.ID, "name": req.Name, "description": req.Description})
	ctx.Set("responseMessage", "更新角色成功")
}

// DeleteRole 通过 POST /delete 实现角色删除
// @Summary 删除角色
// @Tags 角色管理
// @Accept json
// @Produce json
// @Param id body model.Role true "角色ID"
// @Success 200 {string} string "删除成功"
// @Failure 400 {object} model.ErrorResponse
// @Failure 500 {object} model.ErrorResponse
// @Router /api/roles/delete [post]
func (c *RoleController) DeleteRole(ctx *gin.Context) {
	var req struct {
		ID uint `json:"id" binding:"required"`
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, model.ErrorResponse{
			Code:    http.StatusBadRequest,
			Message: "请求参数格式不正确",
			Error:   err.Error(),
		})
		return
	}
	if err := c.service.DeleteRole(req.ID); err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, model.ErrorResponse{
			Code:    http.StatusInternalServerError,
			Message: "删除角色失败",
			Error:   err.Error(),
		})
		return
	}
	ctx.Set("responseData", gin.H{"id": req.ID})
	ctx.Set("responseMessage", "删除角色成功")
}

// GetRole 查询角色（支持通过 ?id= 查询单个，否则查全部）
// @Summary 查询角色
// @Tags 角色管理
// @Param id query int false "角色ID"
// @Success 200 {object} model.Role
// @Success 200 {array} model.Role
// @Router /api/roles [get]
func (c *RoleController) GetRole(ctx *gin.Context) {
	idStr := ctx.Query("id")
	if idStr == "" {
		roles, err := c.service.GetAllRoles()
		if err != nil {
			ctx.AbortWithStatusJSON(http.StatusInternalServerError, model.ErrorResponse{
				Code:    http.StatusInternalServerError,
				Message: "查询角色列表失败",
				Error:   err.Error(),
			})
			return
		}
		ctx.Set("responseData", roles)
		return
	}
	id, err := strconv.Atoi(idStr)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, model.ErrorResponse{
			Code:    http.StatusBadRequest,
			Message: "无效的角色ID",
			Error:   err.Error(),
		})
		return
	}
	role, err := c.service.GetRoleByID(uint(id))
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusNotFound, model.ErrorResponse{
			Code:    http.StatusNotFound,
			Message: "角色未找到",
			Error:   err.Error(),
		})
		return
	}
	ctx.Set("responseData", role)
}
